package hanlder

import (
	"context"
	"fmt"
	opentracing "github.com/opentracing/opentracing-go"
	uuid "github.com/satori/go.uuid"
	jaeger "github.com/uber/jaeger-client-go"
	config "github.com/uber/jaeger-client-go/config"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"order_srv/cart"
	"order_srv/global"
	"order_srv/goods"
	"order_srv/model"
	"order_srv/order"
)

type OrderService struct {
	order.UnimplementedOrderServer
}

// 创建订单
func (o *OrderService) CreateOrder(ctx context.Context, in *order.CreateOrderRequest) (*order.CreateOrderResponse, error) {
	//链路追踪
	cfg := &config.Configuration{
		ServiceName: "create_order",
		Sampler: &config.SamplerConfig{
			Type:  jaeger.SamplerTypeConst,
			Param: 1,
		},
		Reporter: &config.ReporterConfig{
			LogSpans:           true,
			LocalAgentHostPort: fmt.Sprintf("%s:%d", "127.0.0.1", 6831),
		},
	}
	tracer, closer, err := cfg.NewTracer(config.Logger(jaeger.StdLogger))
	if err != nil {
		panic(fmt.Sprintf("ERROR: cannot init Jaeger: %v\n", err))
	}
	opentracing.SetGlobalTracer(tracer)
	defer closer.Close()
	//建立一个父级span
	parentSpan := opentracing.StartSpan("create")

	//子级span
	getCart := opentracing.StartSpan("get_cart", opentracing.ChildOf(parentSpan.Context()))
	//查询购物车中是否存在该商品
	detail, err := global.CartService.CartDetail(context.Background(), &cart.CartDetailRequest{UserId: in.UserId})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "购物车没有该商品")
	}

	getCart.Finish()

	getGoods := opentracing.StartSpan("get_goods", opentracing.ChildOf(parentSpan.Context()))
	//查询商品详情
	goodsDetail, err := global.GoodsService.GetGoodsDetail(context.Background(), &goods.GetGoodsDetailRequest{GoodsId: in.GoodsId})
	if err != nil {
		return nil, status.Errorf(codes.Internal, "商品不存在")
	}
	getGoods.Finish()
	mount := float32(detail.Stock) * goodsDetail.Price

	m := model.Order{
		OrderSn:      fmt.Sprintf("%s", uuid.NewV4()),
		UserId:       in.UserId,
		GoodsId:      in.GoodsId,
		OrderMount:   float64(mount),
		Address:      in.Address,
		SingerName:   in.SingerName,
		SingerMobile: in.SingerMobile,
	}

	create := opentracing.StartSpan("create", opentracing.ChildOf(parentSpan.Context()))
	tx := global.DB.Model(&model.Order{}).Create(&m)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "创建订单失败")
	}
	create.Finish()
	return &order.CreateOrderResponse{OrderId: int32(m.ID)}, nil
}

// 订单详情
func (o *OrderService) GetOrderDetail(ctx context.Context, in *order.GetOrderDetailRequest) (*order.GetOrderDetailResponse, error) {
	var orderinfo model.Order
	tx := global.DB.Model(&model.Order{}).Where(model.Order{OrderSn: in.OrderSn}).First(&orderinfo)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "查询订单详情失败")
	}
	return &order.GetOrderDetailResponse{
		OrderSn:      orderinfo.OrderSn,
		UserId:       orderinfo.UserId,
		GoodsId:      orderinfo.GoodsId,
		PayType:      orderinfo.PayType,
		Status:       orderinfo.Status,
		OrderMount:   float32(orderinfo.OrderMount),
		Address:      orderinfo.Address,
		SingerName:   orderinfo.SingerName,
		SingerMobile: orderinfo.SingerMobile,
	}, nil
}
